package handler

import (
	"2301a/yuekao/api/request"
	"2301a/yuekao/internal/dao"
	"2301a/yuekao/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func ReservationShowings(c *gin.Context) {
	var req request.ReservationReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if user.Id != 1 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "该权限不足",
			"data":    nil,
		})
		return
	}
	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "房源不存在",
			"data":    nil,
		})
		return
	}
	parse, err := time.Parse(time.DateTime, req.ReservationTime)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "当前时间错误",
			"data":    nil,
		})
		return
	}
	if parse.Unix() > parse.UnixMilli() {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "预约时间不能小于当前时间",
			"data":    nil,
		})
		return
	}
	dao.Create(&model.HouseReservation{
		HouseId:         house.Id,
		UserId:          c.GetUint("userId"),
		ReservationTime: parse,
	})
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "预约看房成功",
		"data":    true,
	})
}

func ReservationCancel(c *gin.Context) {
	var req request.ReservationCancelReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var reservation model.HouseReservation
	dao.GetOneById(req.Id, &reservation)
	if reservation.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "取消预约看房失败",
			"data":    nil,
		})
		return
	}
	dao.Delete(&model.HouseReservation{Id: req.Id})
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "取消看房成功",
		"data":    true,
	})
}
